//
//  BADScanViewController.m
//  BAD
//
//  Created by Can on 2018/5/14.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "BADScanViewController.h"
#import "BADSuccessViewController.h"
#import "BADUnSuccessViewController.h"
#import "BADUnSuccessViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"
#import "CADisplayLineImageView.h"

@interface BADScanViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,CLLocationManagerDelegate>{
    CLLocationManager *locationmanager;//定位服务
    NSString *strlatitude;//经度
    NSString *strlongitude;//纬度
    CGFloat height;
}

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) UIImagePickerController *imagePicker;

@property (nonatomic, strong) UIImage *imgPicker;

@property (nonatomic, strong) UIButton *cameraBtn;

@end

@implementation BADScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    height = StatusBarHeight;
    
    strlatitude = @"0";
    
    strlongitude = @"0";
    
    [self getLocation];
    
    [self creatTableView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:NO];
}

- (void)creatTableView
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsHorizontalScrollIndicator = NO;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
    [_tableView setTableHeaderView:[self creatView]];
}

- (UIView *)creatView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 0)];
    
    UIImageView *bioisland = [UIViewControls creatImageView:CGRectMake((SCREENW - 270/2*screenW_6)/2, 133/2*screenW_6, 270/2*screenW_6, 92/2*screenW_6) imageName:@"logo3"];
    [view addSubview:bioisland];
    
//    UIImageView *gifImageView = [UIViewControls creatImageView:CGRectMake(0, CGRectGetMaxY(bioisland.frame) + 35*screenW_6, SCREENW, 501/2*screenW_6) imageName:nil];
//    gifImageView.image = [self sd_animatedGIFNamed:@"MKZ"];
//    [view addSubview:gifImageView];
    
    CADisplayLineImageView *gifImageView = [[CADisplayLineImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(bioisland.frame) + 35*screenW_6, SCREENW, 475/2*screenW_6)];
    [view addSubview:gifImageView];
    [gifImageView setImage:[CADisplayLineImage imageNamed:@"MKZ.gif"]];
    
    UILabel *keep = [self creatLable:CGRectMake(40*screenW_6, CGRectGetMaxY(gifImageView.frame) + 33/2*screenW_6, SCREENW - 80*screenW_6, 11.11*screenW_6) text:@"1. Keep your hands steady while taking photos and make sure to use focus on your phone`s camera."];
    keep.frame = CGRectMake(40*screenW_6, CGRectGetMaxY(gifImageView.frame) + 33/2*screenW_6, SCREENW - 80*screenW_6, [UIViewControls lableHeight:keep]);
    [view addSubview:keep];
    
    UILabel *once = [self creatLable:CGRectMake(40*screenW_6, CGRectGetMaxY(keep.frame) + 15/2*screenW_6, SCREENW - 80*screenW_6, 11.11*screenW_6) text:@"2. Once the examination is successful it can be confirmed as authentic."];
    once.frame = CGRectMake(40*screenW_6, CGRectGetMaxY(keep.frame) + 15/2*screenW_6, SCREENW - 80*screenW_6, [UIViewControls lableHeight:once]);
    [view addSubview:once];
    
    UIButton *pickButton = [UIViewControls creatButtonBackImage:CGRectMake((SCREENW - 294/2*screenW_6)/2, CGRectGetMaxY(once.frame) + 58/2*screenW_6, 294/2*screenW_6, 93/2*screenW_6) imageName:@"camera"];
    [pickButton addTarget:self action:@selector(pick:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:pickButton];
    view.frame = CGRectMake(0, 0, SCREENW, CGRectGetMaxY(pickButton.frame) + 20*screenW_6);
    
    return view;
}

- (void)pick:(UIButton *)btn
{
    [self checkVideoStatus];
}

- (void) checkVideoStatus
{
    //相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
        authStatus ==AVAuthorizationStatusDenied)  //用户已经明确否认了这一照片数据的应用程序访问
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"Whether to allow the APP to access camera rights during photo recognition" preferredStyle:  UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
            // 无权限 引导去开启
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }]];
        [self presentViewController:alert animated:true completion:nil];
        
    }else{
        _imagePicker = [[UIImagePickerController alloc] init];

        _imagePicker.delegate = self;

        _imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
 
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) return;
        [self presentViewController:_imagePicker animated:YES completion:nil];

//        _imagePicker.cameraViewTransform = CGAffineTransformMakeScale(1, 1);
        CGSize screenBounds = [UIScreen mainScreen].bounds.size;
        CGFloat cameraAspectRatio = 4.0f/3.0f;
        CGFloat camViewHeight = screenBounds.width * cameraAspectRatio;
        CGFloat scale = screenBounds.height / camViewHeight;
        _imagePicker.cameraViewTransform = CGAffineTransformMakeTranslation(0, (screenBounds.height - camViewHeight) / 2.0);
        _imagePicker.cameraViewTransform = CGAffineTransformScale(_imagePicker.cameraViewTransform, scale, scale);
        _imagePicker.showsCameraControls  = NO;
        
        UIView *toolView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENH - 100*screenW_6, SCREENW, 100*screenW_6)];
        toolView.backgroundColor = [UIColor blackColor];
        toolView.alpha = 0.5;

        UIButton *cancel = [UIViewControls creatButtonSetImage:CGRectMake(20*screenW_6, 25*screenW_6, 50*screenW_6, 50*screenW_6) imageName:@"arrow_down2"];
        [cancel addTarget:self action:@selector(cancelCamera) forControlEvents:UIControlEventTouchUpInside];
        [toolView addSubview:cancel];

        _cameraBtn = [UIViewControls creatButtonSetImage:CGRectMake((SCREENW - 132/2*screenW_6)/2, (100*screenW_6 -132/2*screenW_6)/2, 132/2*screenW_6, 132/2*screenW_6) imageName:@"Camera_button"];
        [_cameraBtn addTarget:self action:@selector(savePhoto) forControlEvents:UIControlEventTouchUpInside];
        [toolView addSubview:_cameraBtn];

        //把自定义的view设置到imagepickercontroller的overlay属性中
        _imagePicker.cameraOverlayView = toolView;
    }
}

-(void)cancelCamera{
    [_imagePicker dismissViewControllerAnimated:YES completion:^{
    }];
}

-(void)savePhoto{
    _cameraBtn.userInteractionEnabled = NO;
    [_imagePicker takePicture];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"])
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self creatBigImgView:image];
        _imgPicker = [self imageCompressWithSimple:image];
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }
}

- (void)creatBigImgView:(UIImage *)image
{
    //初始化要显示的图片内容的imageView
    UIImageView *browseImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -height, SCREENW, SCREENH + height)];
    [browseImgView setBackgroundColor:[UIColor blackColor]];
    [browseImgView setContentMode:UIViewContentModeScaleAspectFill];
    browseImgView.clipsToBounds = YES;
    //要显示的图片，即要放大的图片
    browseImgView.image = image;
    browseImgView.tag = 1000;
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:browseImgView];
    
    browseImgView.userInteractionEnabled = YES;
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, browseImgView.height - 100*screenW_6, SCREENW, 100*screenW_6)];
    [view setBackgroundColor:[UIColor blackColor]];
    view.alpha = 0.5;
    [browseImgView addSubview:view];
    
    UIButton *cancel = [UIViewControls creatButton:CGRectMake(20*screenW_6, 25*screenW_6, 80*screenW_6, 50*screenW_6) title:@"Retry"];
    [cancel addTarget:self action:@selector(cancelImage) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancel];
    
    UIButton *OK = [UIViewControls creatButton:CGRectMake(SCREENW - 50*screenW_6 - 20*screenW_6, (100*screenW_6 - 50*screenW_6)/2, 50*screenW_6, 50*screenW_6) title:@"OK"];
    [OK addTarget:self action:@selector(okImg) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:OK];
}

- (void)cancelImage
{
    _cameraBtn.userInteractionEnabled = YES;
    
    [self closeView];
    
    [self checkVideoStatus];
}

- (void)okImg
{
    _cameraBtn.userInteractionEnabled = YES;
    
    [self creatAlphaView];
    
    [self closeView];

    [self monitorNetworking];
}

-(void)closeView{

    [[[UIApplication sharedApplication].keyWindow viewWithTag:1000] removeFromSuperview];
}

- (void)creatAlphaView
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, -44, SCREENW, SCREENH + 88)];
    [view setBackgroundColor:[UIColor blackColor]];
    view.tag = 1005;
    view.alpha = 0.5;
    UIApplication *ap = [UIApplication sharedApplication];
    [ap.keyWindow addSubview:view];
    
    CGFloat width = [GetStrWidthAndHeight getStringWidthWith:@"Please Waiting..." andHeigth:15*screenW_6 andFont:[UIFont systemFontOfSize:15*screenW_6]];
    
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 150 + width, 75)];
    [backView setBackgroundColor:[UIColor whiteColor]];
    backView.tag = 1010;
    backView.layer.cornerRadius = 8;
    backView.layer.masksToBounds = YES;
    [ap.keyWindow addSubview:backView];
    backView.center = CGPointMake(ap.keyWindow.centerX, ap.keyWindow.centerY);
    
    UIView *hudView = [[UIView alloc]initWithFrame:CGRectMake(25, 0, 75, 75)];
    [hudView setBackgroundColor:[UIColor whiteColor]];
    [backView addSubview:hudView];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:hudView animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.color = [UIColor whiteColor];
    //11，背景框的最小大小
    hud.minSize = CGSizeMake(25, 25);
    //13,是否强制背景框宽高相等
    hud.square = YES;
    
    UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(100, 25/2, width, 50)];
    lable.text = @"Please Waiting...";
    lable.textColor = [UIColor blackColor];
    lable.font = [UIFont systemFontOfSize:15*screenW_6];
    lable.textAlignment = NSTextAlignmentRight;
    [backView addSubview:lable];
}

#pragma mark - ------------- 监测网络状态 -------------
- (void)monitorNetworking
{
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case -1:
                NSLog(@"未知网络");
                break;
            case 0:
                NSLog(@"网络不可达");
                break;
            case 1:
            {
                NSLog(@"GPRS");
            }
                break;
            case 2:
            {
                NSLog(@"wifi");
            }
                break;
            default:
                break;
        }
        if (status == AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi) {

            [self postImage:self->_imgPicker];

        }else{
            [[[UIApplication sharedApplication].keyWindow viewWithTag:1005] removeFromSuperview];
            [[[UIApplication sharedApplication].keyWindow viewWithTag:1010] removeFromSuperview];
            [HudHelper showAlertViewWithMessage:@"Please check the network"];
        }
    }];
}

- (UIImage*)imageCompressWithSimple:(UIImage*)image{
    CGFloat scaledWidth = 1700;
    CGFloat scaledHeight = 1700/image.size.width * image.size.height;
    
    if (image.size.width > image.size.height) {
        scaledWidth = 1700/image.size.height * image.size.width;
        scaledHeight = 1700;
    }
    CGSize secSize =CGSizeMake(scaledWidth, scaledHeight);
    //TODO:设置新图片的宽高
    UIGraphicsBeginImageContext(secSize); // this will crop
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage= UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

- (void)postImage:(UIImage *)image
{
    NSMutableDictionary *dic = [NSMutableDictionary new];
//    image = [UIImage imageNamed:@"WechatIMG141.jpeg"];
    NSData *imageData = UIImageJPEGRepresentation(image,0.85);
    [dic setValue:@"Maxigenes" forKey:@"app_name"];
    [dic setValue:[BADGetIphone getIP] forKey:@"ip"];
    [dic setValue:@"iOS" forKey:@"dev_os"];
    [dic setValue:[[UIDevice currentDevice] systemVersion] forKey:@"dev_os_ver"];
    [dic setValue:[BADGetIphone getDeviceVersion] forKey:@"dev_model"];
    [dic setValue:strlatitude forKey:@"latitude"];
    [dic setValue:strlongitude forKey:@"longitude"];
//    [dic setValue:@"10" forKey:@"userid"];
//    [dic setValue:@"name" forKey:@"nickname"];
//    [dic setValue:@"1" forKey:@"sex"];
//    [dic setValue:@"url" forKey:@"headimgurl"];

    [HttpRequest PostFileRequestUrl:imageData Dic:dic completion:^(NSDictionary *responseDic) {
//        NSLog(@"responseDic:%@",responseDic);
        [[[UIApplication sharedApplication].keyWindow viewWithTag:1005] removeFromSuperview];
        [[[UIApplication sharedApplication].keyWindow viewWithTag:1010] removeFromSuperview];
        if ([[responseDic objectForKey:@"errcode"] boolValue]) {
            BADUnSuccessViewController *unSuccessVC = [BADUnSuccessViewController new];
            [self.navigationController pushViewController:unSuccessVC animated:YES];
        }else{
            NSString *ID = [[responseDic objectForKey:@"result"] objectForKey:@"prod_id"];
            
            if ([ID intValue] >= 3 && [ID intValue] <= 13) {
                BADUnSuccessViewController *unSuccessVC = [BADUnSuccessViewController new];
                [self.navigationController pushViewController:unSuccessVC animated:YES];
            }else{
                BADSuccessViewController *successVC = [BADSuccessViewController new];
                successVC.ID = ID;
                [self.navigationController pushViewController:successVC animated:YES];
            }
        }
    }];
}

- (UILabel *)creatLable:(CGRect)rect text:(NSString *)text
{
    UILabel *lable = [[UILabel alloc]initWithFrame:rect];
    lable.text = text;
    lable.textColor = [UIColor colorWithHexString:@"bbb9b9"];
    lable.font = [UIFont systemFontOfSize:11.11*screenW_6];
    lable.textAlignment = NSTextAlignmentLeft;
    return lable;
}

-(NSString *)deviceWANIPAddress
{
    NSURL *ipURL = [NSURL URLWithString:@"http://ip.taobao.com/service/getIpInfo.php?ip=myip"];
    NSData *data = [NSData dataWithContentsOfURL:ipURL];
    NSDictionary *ipDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
    NSString *ipStr = nil;
    if (ipDic && [ipDic[@"code"] integerValue] == 0) { //获取成功
        ipStr = ipDic[@"data"][@"ip"];
    }
    return (ipStr ? ipStr : @"");
}

-(void)getLocation
{
    //判断定位功能是否打开
    if ([CLLocationManager locationServicesEnabled]) {
        locationmanager = [[CLLocationManager alloc]init];
        locationmanager.delegate = self;
        [locationmanager requestAlwaysAuthorization];
        [locationmanager requestWhenInUseAuthorization];
        //设置寻址精度
        locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        locationmanager.distanceFilter = 5.0;
        [locationmanager startUpdatingLocation];
    }
}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Turn on [Location Services] to allow [BAD] to get your position" message:@"Please turn on the location service in the system settings (Settings> Privacy> Location Services> On)" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Setting" , nil];
    alertView.delegate = self;
    alertView.tag = 1;
    [alertView show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 1) {
        if (buttonIndex == 1) {
            //跳转到定位权限页面
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if( [[UIApplication sharedApplication]canOpenURL:url] ) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
    }
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [manager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    
    //打印当前的经度与纬度
    strlatitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];
    strlongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    NSLog(@"lat:%@ long:%@",strlatitude,strlongitude);
    
    locationmanager.delegate = nil;
}

- (UIImage *)sd_animatedGIFNamed:(NSString *)name {
    CGFloat scale = [UIScreen mainScreen].scale;
    
    if (scale > 1.0f) {
        NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];
        
        NSData *data = [NSData dataWithContentsOfFile:retinaPath];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
        
        data = [NSData dataWithContentsOfFile:path];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        return [UIImage imageNamed:name];
    }
    else {
        NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];
        
        NSData *data = [NSData dataWithContentsOfFile:path];
        
        if (data) {
            return [UIImage sd_animatedGIFWithData:data];
        }
        
        return [UIImage imageNamed:name];
    }
}

@end
